package com.aat.func.pross;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 记录当前内存信息
 * 
 * @author Sx
 * @version 2013-10-08
 */
public class TopFileUtils {
    private static final Logger logger = LoggerFactory.getLogger(TopFileUtils.class);
    
    public static String writeTopMsg() {
        InputStreamReader isr = null;
        BufferedReader br = null;
        
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        
        String result = "";
        try {
            String cmd = "top -b -n 1 -c  -s -p ";
            Process ps = Runtime.getRuntime().exec(cmd);
            isr = new InputStreamReader(ps.getInputStream());
            br = new BufferedReader(isr);
            File file = new File("/opt/topmsg.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            
            fos = new FileOutputStream(file, true);
            osw = new OutputStreamWriter(fos);
            bw = new BufferedWriter(osw);
            
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
                bw.write(line + "\n");
            }
            result = sb.toString();
        } catch (Exception e) {
            logger.error("writeTopMsg error:" + e);
        } finally {
            try {
                if (bw != null)
                    bw.close();
            } catch (IOException e) {
                logger.error("close bw error:" + e);
            }
            try {
                if (osw != null)
                    osw.close();
            } catch (IOException e) {
                logger.error("close osw error:" + e);
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                logger.error("close fos error:" + e);
            }
            try {
                if (br != null)
                    br.close();
            } catch (IOException e) {
                logger.error("close br error:" + e);
            }
            try {
                if (isr != null)
                    isr.close();
            } catch (IOException e) {
                logger.error("close isr error:" + e);
            }
        }
        return result;
    }
    
    public static void main(String[] args) {
        System.out.println(writeTopMsg());
    }
}